package com.atguigu.gmall.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 微服务之间 远程调用时传递请求头中的用户信息
 *
 */
@Component
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null != requestAttributes){
            HttpServletRequest request =
                    requestAttributes.getRequest();
            if(null != request){
                String userId = request.getHeader("userId");
                if(null != userId){
                    requestTemplate.header("userId",userId);
                }
                String userTempId = request.getHeader("userTempId");
                if(null != userTempId){
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }
    }
}
